<template>
    <div>
        <app-head></app-head>
        <app-body>
            <div class="idle-details-container">
                <div class="details-header">
                    <div class="details-header-user-info">
                        <el-image
                                style="width: 80px; height: 80px;border-radius: 5px;"
                                :src="idleItemInfo.user.avatar"
                                fit="contain"></el-image>
                        <div style="margin-left: 10px;">
                            <div class="details-header-user-info-nickname">{{idleItemInfo.user.nickname}}</div>
                            <div class="details-header-user-info-time">{{idleItemInfo.user.signInTime.substring(0,10)}} 加入平台</div>
                        </div>
                    </div>
                    <div class="details-header-buy" :style="'width:'+(isMaster?'150px;':'280px;')">
                        <div style="color: red;font-size: 18px;font-weight: 600;">￥{{idleItemInfo.idlePrice}}</div>
                        <div v-if="!isMaster&&idleItemInfo.idleStatus!==1" style="color: red;font-size: 16px;">闲置已下架或删除</div>
                        <el-button v-if="!isMaster&&idleItemInfo.idleStatus===1" type="danger" plain @click="buyButton(idleItemInfo)">立即购买</el-button>
                        <el-button v-if="!isMaster&&idleItemInfo.idleStatus===1" type="primary" plain @click="favoriteButton(idleItemInfo)">{{isFavorite?'取消收藏':'收藏'}}</el-button>
                        <el-button v-if="isMaster&&idleItemInfo.idleStatus===1" type="danger" @click="changeStatus(idleItemInfo,2)" plain>下架</el-button>
                        <el-button v-if="isMaster&&idleItemInfo.idleStatus===2" type="primary" @click="changeStatus(idleItemInfo,1)" plain>重新上架</el-button>
                    </div>
                </div>

                <div class="details-info">
                    <div class="details-info-title">{{idleItemInfo.idleName}}</div>
                    <div class="details-info-main" v-html="idleItemInfo.idleDetails">
                        {{idleItemInfo.idleDetails}}
                    </div>
                    <div class="details-picture">
                        <el-image v-for="(imgUrl,i) in idleItemInfo.pictureList"
                        :key="i"
                                  style="width: 90%;margin-bottom: 2px;"
                                  :src="imgUrl"
                                  fit="contain"></el-image>
                    </div>
                    <el-button v-if="!isMaster" type="primary" @click="openChat" style="margin-top: 20px;">私聊卖家</el-button>
                </div>

                 <!-- 优化后的聊天对话框 -->
                 <el-dialog
        :title="'与 ' + idleItemInfo.user.nickname + ' 的对话'"
        :visible.sync="showChatDialog"
        width="60%"
        class="chat-dialog"
        @opened="focusInput"
        @closed="closeChat"
    >
        <div class="chat-container">
            <div class="chat-messages" ref="messageContainer">
                <div 
                    v-for="(msg, index) in messages" 
                    :key="index" 
                    class="message-item"
                    :class="{ 'self': msg.sender === currentUser }"
                >
                    <div class="message-user">
                        <el-avatar 
                            v-if="msg.sender !== currentUser"
                            :size="32" 
                            :src="idleItemInfo.user.avatar" 
                        />
                        <span class="sender-name" v-if="msg.sender !== currentUser">
                            {{ idleItemInfo.user.nickname }}
                        </span>
                        <span class="sender-name self-name" v-else>
                            {{ $globalData.userInfo.username || '我' }}
                        </span>
                        <el-avatar 
                            v-if="msg.sender === currentUser"
                            :size="32" 
                            :src="$globalData.userInfo.avatar" 
                        />
                    </div>
                    <div class="message-content">{{ msg.content }}</div>
                    <div class="message-time">{{ formatTime(msg.createTime) }}</div>
                </div>
            </div>
            
            <div class="chat-input-container">
                <el-input
                    ref="messageInput"
                    v-model="newMessage"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入消息..."
                    @keyup.enter.native="sendChatMessage"
                    class="chat-input"
                ></el-input>
                <el-button 
                    type="primary" 
                    @click="sendChatMessage"
                    class="send-button"
                >
                    发送
                </el-button>
            </div>
        </div>
    </el-dialog>

                <div class="message-container" id="replyMessageLocation">
                    <div class="message-title">全部留言</div>
                    <div class="message-send">
                        <div v-if="isReply" style="padding-bottom: 10px;">
                            <el-button type="info" @click="cancelReply">回复：{{replyData.toMessage}} @{{replyData.toUserNickname}} <i class="el-icon-close el-icon--right"></i></el-button>
                        </div>
                        <el-input
                                type="textarea"
                                autosize
                                placeholder="留言提问..."
                                v-model="messageContent"
                                maxlength="200"
                                show-word-limit>
                        </el-input>
                        <div class="message-send-button">
                            <el-button plain @click="sendComment">发送留言</el-button>
                        </div>
                    </div>
                    <div>
                        <div v-for="(mes,index) in messageList" class="message-container-list">
                            <div class="message-container-list-left">
                                <el-image
                                        style="width: 55px; height: 55px;border-radius: 5px;"
                                        :src="mes.fromU.avatar"
                                        fit="contain"></el-image>
                                <div class="message-container-list-text">
                                    <div class="message-nickname">{{mes.fromU.nickname}}
                                        {{mes.toU.nickname?' @'+mes.toU.nickname+'：'+
                                        mes.toM.content.substring(0,10)+
                                        (mes.toM.content.length>10?'...':''):''}}</div>
                                    <div class="message-content" v-html="mes.content">{{mes.content}}</div>
                                    <div class="message-time">{{mes.createTime}}</div>
                                </div>
                            </div>
                            <div class="message-container-list-right">
                                <el-button style="float: right;"  plain @click="replyMessage(index)">回复</el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
          
        </app-body>
    </div>
</template>

<script>
    import AppHead from '../common/AppHeader.vue';
    import AppBody from '../common/AppPageBody.vue'
    import AppFoot from '../common/AppFoot.vue'
    import SockJS from 'sockjs-client'
    import Stomp from 'stompjs'
    import dayjs from 'dayjs'
    import service, { forceLogout } from '../../utils/request'

    // 获取token的辅助函数
    const getToken = () => {
        const token = localStorage.getItem('token');
        return (token && token.trim()) || null;
    };

    export default {
        name: "idle-details",
        components: {
            AppHead,
            AppBody,
            AppFoot
        },
        data() {
            return {
                 // 新增连接状态相关变量
    reconnectAttempts: 0,
    maxReconnectAttempts: 5,
    heartbeatInterval: null,
    privateSubscription: null,
    sentSubscription: null,
                subscriptions: {}, // 新增订阅存储对象
                stompClient: null, // 确保已定义
                currentUser: null,
                showChatDialog: false,
                messages: [],
                newMessage: '',
                currentUser: null,
                stompClient: null,
                messageContent:'',
                toUser:null,
                toMessage:null,
                isReply:false,
                replyData:{
                    toUserNickname:'',
                    toMessage:''
                },
                messageList:[],
                idleItemInfo:{
                    id:'',
                    idleName:'',
                    idleDetails:'',
                    pictureList:[],
                    idlePrice:0,
                    idlePlace:'',
                    idleLabel:'',
                    idleStatus:-1,
                    userId:'',
                    user:{
                        avatar:'',
                        nickname:'',
                        signInTime:''
                    },
                },
                isMaster:false,
                isFavorite:true,
                favoriteId:0
            };
        },
        created() {
            const socket = new SockJS('http://localhost:8080/ws');
            const stompClient = Stomp.over(socket);
            const token = localStorage.getItem('token');
            let id=this.$route.query.id;
            this.$api.getIdleItem({
                id:id
            }).then(res=>{
                console.log(res);
                if(res.data){
                    let list=res.data.idleDetails.split(/\r?\n/);
                    let str='';
                    for(let i=0;i<list.length;i++){
                        str+='<p>'+list[i]+'</p>';
                    }
                    res.data.idleDetails=str;
                    res.data.pictureList=JSON.parse(res.data.pictureList);
                    this.idleItemInfo=res.data;

                    // 使用JWT令牌认证，从用户信息获取用户ID
                    this.$api.getUserInfo().then(res => {
                        console.log("idle的res结果为",res);
                            if (res.status_code === 1 && res.data) {
                                const userId = res.data.id;
                                console.log('userid', userId);
                                // 设置当前用户ID，用于聊天功能
                                this.currentUser = userId;
                                if (userId == this.idleItemInfo.userId) {
                                    console.log('isMaster');
                                    this.isMaster = true;
                                }
                                this.checkFavorite();
                                this.getAllIdleMessage();
                        } else {
                            console.warn('未获取到用户信息');
                        }
                    }).catch(err => {
                        console.error('获取用户信息失败', err);
                    });
                }
                $('html,body').animate({
                    scrollTop: 0
                }, {duration: 500, easing: "swing"});
            });
            // 其他created代码保持不变
            this.initWebSocket(); // 初始化WebSocket连接
        },
        beforeDestroy() {
            this.disconnectWebSocket();
        },
        methods: {
            // 断开WebSocket连接
            disconnectWebSocket() {
            if (this.stompClient) {
                clearInterval(this.heartbeatInterval);
                if (this.privateSubscription) this.privateSubscription.unsubscribe();
                if (this.sentSubscription) this.sentSubscription.unsubscribe();
                if (this.stompClient.connected) {
                    this.stompClient.disconnect();
                }
            }
        },
            getAllIdleMessage(){
                this.$api.getAllIdleMessage({
                    idleId:this.idleItemInfo.id
                }).then(res=>{
                    if(res.status_code===1){
                        this.messageList=res.data;
                    }
                }).catch(()=>{
                })
            },
           // 新增：对话框打开后自动聚焦输入框
    focusInput() {
      this.$nextTick(() => {
        const input = this.$refs.messageInput;
        if (input && input.focus) {
          input.focus();
        }
      });
    },
    
    // 修改 openChat 方法
    async openChat() {
            if (!this.checkAuth()) return;
            
            this.showChatDialog = true;
            
            try {
                if (!this.stompClient || !this.stompClient.connected) {
                    await this.initWebSocket();
                }
                
                this.loadChatHistory();
                this.focusInput();
            } catch (error) {
                console.error('打开聊天失败:', error);
                this.$message.error('无法建立聊天连接');
            }
        },
    // 加载聊天历史
    loadChatHistory() {
            if (!this.idleItemInfo.userId) return;
            
            this.$api.service.get('/chat/private-history', {
                params: { targetUser: this.idleItemInfo.userId }
            }).then(res => {
                if (res.status_code === 1) {
                    this.messages = res.data.map(msg => ({
                        ...msg,
                        isSelf: msg.sender === this.currentUser
                    }));
                    this.scrollToBottom();
                }
            }).catch(console.error);
        },
    // 分离加载消息逻辑
    loadChatMessages() {
      this.$api.service.get('/chat/item-messages', { 
        params: { 
          itemId: this.idleItemInfo.id,
          targetUserId: this.idleItemInfo.userId
        } 
      }).then(res => {
        if (res.status_code === 1) {
          this.messages = res.data;
          this.scrollToBottom();
        }
      });
    },
            
            proceedWithChat() {
                this.showChatDialog = true;
                
                // 加载历史消息
                this.$api.service.get('/chat/item-messages', { 
                    params: { 
                        itemId: this.idleItemInfo.id,
                        targetUserId: this.idleItemInfo.userId // 确保与卖家聊天
                    } 
                }).then(res => {
                    if (res.status_code === 1) {
                        this.messages = res.data;
                        this.$nextTick(() => {
                            this.scrollToBottom();
                        });
                    } else {
                        
                        this.$message.warning('获取聊天记录失败，但您仍可以发送新消息');
                    }
                }).catch(err => {
                   
                    this.$message.warning('获取聊天记录失败，但您仍可以发送新消息');
                });
                
                // 初始化WebSocket连接
                this.initWebSocket();
            },
            // 发送聊天消息
            async sendChatMessage() {
            if (!this.newMessage.trim()) {
                this.$message.error("消息不能为空！");
                return;
            }
            
            if (!this.currentUser || !this.idleItemInfo.userId) {
                this.$message.error("用户信息未加载完成");
                return;
            }

            const message = {
                content: this.newMessage.trim(),
                sender: this.currentUser,
                receiver: this.idleItemInfo.userId,
                createTime: new Date().toISOString()
            };

            try {
                if (!this.stompClient.connected) {
                    await this.initWebSocket();
                }
                
                await this.stompClient.safeSend('/app/private', message);
                
                // 乐观更新
                this.messages.push({
                    ...message,
                    isSelf: true
                });
                this.newMessage = '';
                this.scrollToBottom();
                
            } catch (e) {
                console.error('发送失败:', e);
                this.$message.error('发送消息失败');
            }
        },
            sendItemMessage(message) {
                    if (!this.stompClient || !this.stompClient.connected) {
                        this.fallbackSendMessage(message);
                        return;
                    }

                    // 添加必要头信息
                    const headers = {
                        'Authorization': `Bearer ${getToken()}`,
                        'content-type': 'application/json'
                    };

                    try {
                        this.stompClient.send(
                        `/app/item/${message.itemId}`,
                        headers,
                        JSON.stringify(message)
                        );
                    } catch (error) {
                        console.error("WebSocket发送失败:", error);
                        this.fallbackSendMessage(message);
                    }
                    },
            
            fallbackSendMessage(message) {
                // 降级方案：使用HTTP API
                const token = getToken();
                if (!token) {
                    forceLogout();
                    return;
                }
                
                // 使用统一的 axios 实例发送请求
                service.post('/chat/send', message)
                    .then(res => {
                        if (res.status_code === 1) {
                            console.log("HTTP API发送消息成功");
                        } else {
                            console.error('发送消息失败:', res);
                            this.$message.error('发送消息失败: ' + (res.msg || '未知错误'));
                        }
                    })
                    .catch(err => {
                        console.error('发送消息异常:', err);
                        if (err.response && err.response.status === 401) {
                            forceLogout();
                        } else {
                            this.$message.error('发送消息失败，请检查网络连接');
                        }
                    });
            },
             // 初始化WebSocket连接
             // 初始化WebSocket连接 (与message.vue完全一致)
             initWebSocket() {
  return new Promise((resolve, reject) => {
    // 断开旧连接
    if (this.stompClient && this.stompClient.connected) {
      this.stompClient.disconnect();
    }

    const socket = new SockJS('http://localhost:8081/ws');
    this.stompClient = Stomp.over(socket);
    this.stompClient.debug = () => {};

    // 定义 safeSend 方法原型
    this.stompClient.safeSend = (destination, body, headers = {}) => {
      return new Promise((resolveSend, rejectSend) => {
        if (!this.stompClient.connected) {
          rejectSend(new Error('STOMP 连接未就绪'));
          return;
        }
        try {
          this.stompClient.send(
            destination,
            { ...headers, 'content-type': 'application/json' },
            JSON.stringify(body)
          );
          resolveSend();
        } catch (e) {
          rejectSend(e);
        }
      });
    };

    const connectHeaders = {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
      'X-User-ID': this.$globalData.userInfo.id
    };

    this.stompClient.connect(connectHeaders, () => {
      console.log('✅ WebSocket连接成功');
      
      // 自动订阅关键通道
      this.subscribeToPrivateQueue();
      this.subscribeToSentQueue();
      
      resolve(true);
    }, (error) => {
      console.error('连接失败:', error);
      reject(error);
    });
  });
},
// 新增心跳检测方法
startHeartbeat() {
            this.heartbeatInterval = setInterval(() => {
                if (!this.stompClient.connected) {
                    console.warn('心跳检测: 连接断开，尝试重连...');
                    this.initWebSocket();
                }
            }, 15000);
        },

// 新增错误处理方法
handleConnectionError(error) {
            if (this.reconnectAttempts < this.maxReconnectAttempts) {
                this.reconnectAttempts++;
                const delay = Math.min(5000 * Math.pow(2, this.reconnectAttempts), 30000);
                setTimeout(() => this.initWebSocket(), delay);
            } else {
                this.$message.error('连接失败，请刷新页面');
            }
        },
// 订阅私有队列 (与message.vue完全一致)
subscribeToPrivateQueue() {
            if (!this.stompClient || !this.stompClient.connected) return;

            if (this.privateSubscription) {
                this.privateSubscription.unsubscribe();
            }

            const userId = this.currentUser;
            this.privateSubscription = this.stompClient.subscribe(
                `/user/${userId}/queue/private`,
                (message) => {
                    try {
                        const msg = JSON.parse(message.body);
                        this.handlePrivateMessage(msg);
                    } catch (e) {
                        console.error('消息解析失败:', e);
                    }
                },
                { 
                    'Authorization': `Bearer ${getToken()}`,
                    'X-User-ID': this.currentUser,
                    'id': `sub-${userId}-private`
                }
            );
        },
// 新增订阅发送确认队列
subscribeToSentQueue() {
            if (!this.stompClient || !this.stompClient.connected) return;

            if (this.sentSubscription) {
                this.sentSubscription.unsubscribe();
            }

            const userId = this.currentUser;
            this.sentSubscription = this.stompClient.subscribe(
                `/user/${userId}/queue/sent`,
                (message) => {
                    const msg = JSON.parse(message.body);
                    console.log('发送确认:', msg);
                },
                { 
                    'Authorization': `Bearer ${getToken()}`,
                    'id': `sub-${userId}-sent`
                }
            );
        },


            // 处理收到的私聊消息
            handlePrivateMessage(msg) {
            if (!msg.sender || !msg.receiver || !msg.content) {
                console.error('无效消息结构:', msg);
                return;
            }

            // 确保消息属于当前会话
            const isCurrentChat = 
                (msg.sender === this.idleItemInfo.userId && msg.receiver === this.currentUser) ||
                (msg.receiver === this.idleItemInfo.userId && msg.sender === this.currentUser);
            
            if (isCurrentChat) {
                this.messages.push({
                    ...msg,
                    isSelf: msg.sender === this.currentUser
                });
                this.scrollToBottom();
                
                if (msg.sender !== this.currentUser) {
                    this.sendReadReceipt(msg.id);
                }
            }
        },
                    subscribeToItemChat(itemId) {
                        if (!this.stompClient.connected) return;

                        const subscription = this.stompClient.subscribe(
                            `/topic/item/${itemId}`,
                            (message) => {
                            try {
                                const msg = JSON.parse(message.body);
                                // 验证消息是否属于当前聊天
                                if (msg.itemId === this.idleItemInfo.id && 
                                    (msg.sender === this.idleItemInfo.userId || 
                                    msg.receiver === this.currentUser)) {
                                this.handleIncomingMessage(msg);
                                }
                            } catch (e) {
                                console.error("消息解析失败:", e);
                            }
                            },
                            { 'Authorization': `Bearer ${getToken()}` } // 订阅时也携带token
                        );
                        
                        // 存储subscription以便后续取消
                        this.subscriptions[itemId] = subscription;
                        },
            handleIncomingMessage(msg) {
              // 验证基础字段
              if (!msg.sender || !msg.receiver || !msg.content) {
                console.error('无效消息结构:', msg);
                return;
              }

              // 仅处理当前商品的消息
              if (msg.itemId !== this.idleItemInfo.id) return;

              // 标记是否为自己发送的消息
              msg.isSelf = msg.sender === this.currentUser;

              // 添加消息
              this.messages.push(msg);
              
              this.$nextTick(() => {
                this.scrollToBottom();
              });

              // 可选：发送阅读回执
              if (!msg.isSelf) {
                this.sendReadReceipt(msg.id);
              }
            },

            // 发送阅读回执
            sendReadReceipt(messageId) {
            this.$api.service.post('/chat/mark-read', { messageId })
                .catch(console.error);
        },
           // 滚动到底部
           scrollToBottom() {
            this.$nextTick(() => {
                const container = this.$refs.messageContainer;
                if (container) container.scrollTop = container.scrollHeight;
            });
        },
             // 格式化时间
             formatTime(time) {
            return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
        },
            checkFavorite(){
                this.$api.checkFavorite({
                    idleId:this.idleItemInfo.id
                }).then(res=>{
                    if(!res.data){
                        this.isFavorite=false;
                    }else {
                        this.favoriteId=res.data;
                    }
                })
            },
            // 检查JWT令牌是否有效
            checkAuth() {
                const token = localStorage.getItem('token');
                if (!token) {
                    this.$message.error('用户未登录或登录已过期');
                    this.$router.push('/login');
                    return false;
                }
                return true;
            },
            // 关闭聊天对话框
            closeChat() {
                this.showChatDialog = false;
                // 不需要清空消息，保留聊天记录
            },
            replyMessage(index){
                if (!this.checkAuth()) return;
                
                $('html,body').animate({
                    scrollTop: $("#replyMessageLocation").offset().top-600
                }, {duration: 500, easing: "swing"});
                this.isReply=true;
                this.replyData.toUserNickname=this.messageList[index].fromU.nickname;
                this.replyData.toMessage=this.messageList[index].content.substring(0,10)+(this.messageList[index].content.length>10?'...':'');
                this.toUser=this.messageList[index].userId;
                this.toMessage=this.messageList[index].id;
            },
            changeStatus(idle,status){
                if (!this.checkAuth()) return;
                
                this.$api.updateIdleItem({
                    id:idle.id,
                    idleStatus:status
                }).then(res=>{
                    console.log(res);
                    if(res.status_code===1){
                        this.idleItemInfo.idleStatus=status;
                    }else {
                        this.$message.error(res.msg)
                    }
                });
            },
            buyButton(idleItemInfo){
                if (!this.checkAuth()) return;
                
                this.$api.addOrder({
                    idleId:idleItemInfo.id,
                    orderPrice:idleItemInfo.idlePrice,
                }).then(res=>{
                    console.log(res);
                    if(res.status_code===1)
                    {
                        this.$router.push({path: '/order', query: {id: res.data.id}});
                    }else {
                        this.$message.error(res.msg)
                    }
                }).catch(e=>{

                })
            },
            favoriteButton(idleItemInfo){
                if (!this.checkAuth()) return;
                
                if(this.isFavorite){
                    this.$api.deleteFavorite({
                        id: this.favoriteId
                    }).then(res=>{
                        if(res.status_code===1){
                            this.$message({
                                message: '已取消收藏！',
                                type: 'success'
                            });
                            this.isFavorite=false;
                        }else {
                            this.$message.error(res.msg)
                        }
                    }).catch(e=>{
                    })
                }else {
                    this.$api.addFavorite({
                        idleId:idleItemInfo.id
                    }).then(res=>{
                        console.log("idle的添加喜好模块res结果为",res);
                        if(res.status_code===1){
                            this.$message({
                                message: '已收藏！',
                                type: 'success'
                            });
                            this.isFavorite=true;
                            this.favoriteId=res.data;
                        }else {
                            this.$message.error(res.msg)
                        }
                    }).catch(e=>{
                    })
                }
            },
            cancelReply(){
                this.isReply=false;
                this.toUser=this.idleItemInfo.userId;
                this.toMessage=null;
                this.replyData.toUserNickname='';
                this.replyData.toMessage='';
            },
            sendComment(){
                if (!this.checkAuth()) return;
                
                let content = this.messageContent.trim();
                if(this.toUser == null){
                    this.toUser = this.idleItemInfo.userId;
                }
                if(content){
                    let contentList = content.split(/\r?\n/);
                    let contenHtml = contentList[0];
                    for(let i=1; i<contentList.length; i++){
                        contenHtml += '<br>' + contentList[i];
                    }
                    this.$api.sendMessage({
                        idleId: this.idleItemInfo.id,
                        content: contenHtml,
                        toUser: this.toUser,
                        toMessage: this.toMessage
                    }).then(res => {
                        if(res.status_code === 1){
                            this.$message({
                                message: '留言成功！',
                                type: 'success'
                            });
                            this.messageContent = '';
                            this.cancelReply();
                            this.getAllIdleMessage();
                        } else {
                            this.$message.error("留言失败！" + res.msg);
                        }
                    }).catch(() => {
                        this.$message.error("留言失败！");
                    });
                } else {
                    this.$message.error("留言为空！");
                }
            }
        },
    }
</script>

<style scoped>
    .idle-details-container {
        min-height: 85vh;
    }
/* 新增聊天样式 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 400px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 10px;
  background-color: #f5f7fa;
}

.chat-input-container {
  display: flex;
  gap: 10px;
}

.chat-input {
  flex: 1;
}

.send-button {
  height: auto;
  align-self: flex-end;
}

.message-item {
  margin-bottom: 15px;
}

.message-item.self {
  text-align: right;
}

.message-user {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.message-user .el-avatar {
  margin: 0 8px;
}

.sender-name {
  font-size: 14px;
  color: #606266;
}

.self-name {
  order: 1; /* 将名字放在右侧 */
  margin-right: 8px;
}

.message-content {
  display: inline-block;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f0f2f5;
  max-width: 70%;
  word-break: break-word;
}

.message-item.self .message-content {
  background-color: #409eff;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
    .details-header {
        height: 80px;
        border-bottom: 10px solid #f6f6f6;
        display: flex;
        justify-content: space-between;
        padding: 20px;
        align-items: center;
    }

    .chat-dialog {
        display: flex;
        flex-direction: column;
    }

    .chat-messages {
        height: 300px;
        overflow-y: auto;
        padding: 10px;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        margin-bottom: 10px;
    }

    .message-item {
        margin-bottom: 10px;
        max-width: 70%;
    }

    .message-item.self {
        margin-left: auto;
        text-align: right;
    }

    .message-content {
        background-color: #f0f0f0;
        padding: 8px 12px;
        border-radius: 4px;
        display: inline-block;
    }

    .message-item.self .message-content {
        background-color: #007bff;
        color: white;
    }

    .message-time {
        font-size: 12px;
        color: #888;
        margin-top: 4px;
    }

    .chat-input {
        display: flex;
        align-items: flex-start;
    }

    .chat-input .el-input {
        flex-grow: 1;
        margin-right: 10px;
    }

    .details-header-user-info {
        display: flex;
    }

    .details-header-user-info-nickname {
        font-weight: 600;
        font-size: 18px;
        margin-bottom: 10px;
    }

    .details-header-user-info-time {
        font-size: 12px;
        color: #555555;
    }

    .details-header-buy {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 50px;
        width: 280px;
    }

    .details-info {
        padding: 20px 50px;
    }

    .details-info-title {
        font-size: 22px;
        font-weight: 600;
        margin-bottom: 20px;

    }

    .details-info-main {
        font-size: 17px;
        color: #121212;
        line-height: 160%;
    }

    .details-picture {
        margin: 20px 0;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .message-container {
        min-height: 100px;
        border-top: 10px solid #f6f6f6;
        padding: 20px;
    }

    .message-title {
        font-size: 20px;
        font-weight: 600;
        margin-bottom: 20px;
    }
    .message-send{
        min-height: 60px;
    }
    .message-send-button{
        margin-top: 10px;
        display: flex;
        justify-content: flex-end;
    }
    .message-container-list{
        min-height: 60px;
        border-top: 1px solid #eeeeee;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 0;
    }
    .message-container-list:first-child{
        border-top:none;
    }
    .message-container-list-left{
        width: 850px;
        display: flex;
    }
    .message-container-list-right{
        width: 100px;
    }
    .message-container-list-text{
        margin-left: 10px;
    }
    .message-nickname{
        font-weight: 600;
        font-size: 18px;
        padding-bottom: 5px;
    }
    .message-content{
        font-size: 16px;
        padding-bottom: 15px;
        color: #555555;
        width: 770px;
    }
    .message-time{
        font-size: 13px;
        color: #555555;
    }
</style>